using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Reflection;

namespace WeatherSystem.API.Controllers
{
    /// <summary>
    /// API文档和帮助控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [AllowAnonymous]
    public class DocumentationController : ControllerBase
    {
        /// <summary>
        /// 获取API信息
        /// </summary>
        /// <returns>API基本信息</returns>
        [HttpGet("info")]
        public IActionResult GetApiInfo()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var version = assembly.GetName().Version?.ToString() ?? "1.0.0";
            
            return Ok(new
            {
                Name = "Weather System API",
                Version = version,
                Description = "A comprehensive weather data management system",
                BuildDate = System.IO.File.GetCreationTime(assembly.Location),
                Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production",
                Features = new[]
                {
                    "JWT Authentication",
                    "Role-based Authorization", 
                    "Rate Limiting",
                    "Response Compression",
                    "Redis Caching",
                    "Background Jobs",
                    "Health Checks",
                    "CQRS Pattern",
                    "EAV Data Model"
                },
                Endpoints = new
                {
                    ApiDocs = "/api-docs",
                    Health = "/health",
                    Metrics = "/metrics",
                    Background = "/hangfire"
                }
            });
        }

        /// <summary>
        /// 获取API端点列表
        /// </summary>
        /// <returns>所有可用的API端点</returns>
        [HttpGet("endpoints")]
        public IActionResult GetEndpoints()
        {
            var endpoints = new[]
            {
                new { Method = "GET", Path = "/api/weather", Description = "获取天气数据列表（支持分页和筛选）" },
                new { Method = "GET", Path = "/api/weather/city/{cityId}", Description = "获取指定城市的天气数据" },
                new { Method = "GET", Path = "/api/weather/latest/{cityId}", Description = "获取指定城市的最新天气数据" },
                new { Method = "GET", Path = "/api/weather/history/{cityId}", Description = "获取指定城市的历史天气数据" },
                new { Method = "POST", Path = "/api/weather/simulate", Description = "模拟生成天气数据" },
                new { Method = "GET", Path = "/api/weather/cities", Description = "获取所有活跃城市列表" },
                new { Method = "POST", Path = "/api/weather/cities", Description = "添加新城市" },
                new { Method = "PUT", Path = "/api/weather/cities/{id}", Description = "更新城市信息" },
                new { Method = "DELETE", Path = "/api/weather/cities/{id}", Description = "删除城市" },
                new { Method = "PATCH", Path = "/api/weather/cities/{id}/status", Description = "切换城市状态" },
                new { Method = "GET", Path = "/api/statistics/overview", Description = "获取统计概览" },
                new { Method = "GET", Path = "/api/statistics/range/{cityId}", Description = "获取指定时间范围的统计数据" },
                new { Method = "POST", Path = "/api/auth/login", Description = "用户登录" },
                new { Method = "POST", Path = "/api/auth/register", Description = "用户注册" },
                new { Method = "POST", Path = "/api/auth/refresh", Description = "刷新访问令牌" },
                new { Method = "POST", Path = "/api/auth/logout", Description = "用户登出" },
                new { Method = "GET", Path = "/api/metrics/definitions", Description = "获取指标定义列表" },
                new { Method = "POST", Path = "/api/metrics/definitions", Description = "创建新指标定义" },
                new { Method = "PUT", Path = "/api/metrics/definitions/{id}", Description = "更新指标定义" },
                new { Method = "DELETE", Path = "/api/metrics/definitions/{id}", Description = "删除指标定义" },
                new { Method = "GET", Path = "/health", Description = "系统健康检查" },
                new { Method = "GET", Path = "/api-docs", Description = "API文档（Swagger UI）" }
            };

            return Ok(new
            {
                TotalEndpoints = endpoints.Length,
                Endpoints = endpoints.GroupBy(e => e.Path.Split('/')[2]).ToDictionary(
                    g => g.Key,
                    g => g.ToArray()
                )
            });
        }

        /// <summary>
        /// 获取数据模型说明
        /// </summary>
        /// <returns>数据模型结构说明</returns>
        [HttpGet("models")]
        public IActionResult GetModels()
        {
            return Ok(new
            {
                WeatherData = new
                {
                    Description = "天气数据实体",
                    Properties = new
                    {
                        Id = "唯一标识符（GUID）",
                        CityId = "关联城市ID",
                        RecordedAt = "记录时间",
                        Source = "数据来源",
                        Metrics = "动态指标列表（EAV模式）"
                    }
                },
                City = new
                {
                    Description = "城市实体",
                    Properties = new
                    {
                        Id = "唯一标识符（GUID）",
                        Name = "城市名称",
                        Country = "国家",
                        Latitude = "纬度",
                        Longitude = "经度",
                        TimeZone = "时区",
                        IsActive = "是否启用"
                    }
                },
                MetricDefinition = new
                {
                    Description = "指标定义（EAV模式）",
                    Properties = new
                    {
                        Key = "指标键名",
                        DisplayName = "显示名称",
                        DataType = "数据类型（decimal, int, string, boolean）",
                        Unit = "单位",
                        Description = "描述",
                        IsActive = "是否启用"
                    }
                },
                PaginatedResult = new
                {
                    Description = "分页结果通用格式",
                    Properties = new
                    {
                        Data = "数据列表",
                        Total = "总记录数",
                        Page = "当前页码",
                        PageSize = "每页大小",
                        TotalPages = "总页数"
                    }
                }
            });
        }

        /// <summary>
        /// 获取认证和授权说明
        /// </summary>
        /// <returns>认证授权机制说明</returns>
        [HttpGet("auth")]
        public IActionResult GetAuthInfo()
        {
            return Ok(new
            {
                AuthenticationType = "JWT Bearer Token",
                TokenExpiry = "24 hours",
                RefreshTokenExpiry = "7 days",
                Roles = new[]
                {
                    new { Name = "Admin", Permissions = "完全访问权限，包括用户管理、系统配置" },
                    new { Name = "User", Permissions = "基本数据访问权限，可查看和分析数据" },
                    new { Name = "ReadOnly", Permissions = "只读权限，仅可查看数据" }
                },
                Usage = new
                {
                    Login = "POST /api/auth/login with username/password",
                    Header = "Authorization: Bearer <your-jwt-token>",
                    Refresh = "POST /api/auth/refresh with refresh token"
                }
            });
        }
    }
}